#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" Support for discovering and loading Tack modules at runtime.

To load modules, call load_mods with the a config file and the OS
environ, WSGI environ, or your own mapping.
"""
import os
import sys
from logging import debug
from functools import partial

from tack.lib import import_attr
from tack.lib.configfile import ConfigFile


def mod_info(module):
    """ Creates mapping of module  and meta data.

    @param module module instance
    @return new dictionary with keys 'module', 'meta'
    """
    return dict(module=module, meta=mod_meta(module))


def mod_meta(module):
    """ Returns dict of metadata for a given module.

    @param module module instance
    @return dict of metadata
    """
    getr = partial(getattr, module)
    return {
        'name' : getr('__name__', 'none'),
        'title' : getr('title', 'none'),
        'version' : getr('version', 0),
        'description' : getr('description', ''),
        }


def load_mods(config, environ, key='TACKMODDIRS'):
    actv = config.getdecoded('activemodules', [])
    dirs = environ.get(key, '')
    if dirs and dirs not in sys.path:
        sys.path.insert(0, dirs)
    mods = [__import__(name) for name in actv]
    sys.path.pop(0)
    return mods


def load_config(environ, filename='config.ini', key='TACKSITEDIR'):
    """ Loads and reads the site config file if available.

    >>> import os
    >>> if os.name == 'nt':
    ...     config = load_config({'TACKSITEDIR':'../richardson-voc'})
    ... else:
    ...     config = load_config({'TACKSITEDIR':'../tack-sites/richardson-voc'})
    >>> config
    {...}

    @param environ mapping
    @keyparam filename='config.ini' name of config file
    @keyparam key='TACKSITEDIR' key naming site directory within environ
    @return site configuration, or None
    """
    site = environ.get(key, '')
    conf = os.path.join(site, filename) if site else None
    return ConfigFile(conf) if conf else None


def load_urls(mods):
    for mod in mods:
        name = mod.__name__
        for url in __import__('%s.urls' % name, fromlist=name).urls:
            yield url
